package com.generate;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.generate.config.CustomizePackageConfig;
import lombok.Data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GenerateMapper
 * @Description: TODO(代码生成)
 * @author lixin
 * @date 2019年5月3日 下午1:11:42
 * @version V1.0
 */
@Data
public class GenerateMapper {

	//	private static String tableNames[] = {"t_sys_dept","t_sys_dept_role","t_sys_menu","t_sys_role","t_sys_role_menu","t_sys_user","t_sys_user_role"}; // 需要生成代码的表名
	private static String tableNames[] = {"t_sys_dept"}; // 需要生成代码的表名

	private static String projectPackageName = ".hclc.demo"; // 工程名,例如:hsx-core-service,只取service

	private static String businessPackageName = "model";// 业务包名，例如：hsx-core-service工程里的email,则填写.email

	private static String documentPackageName = "document";//ES document包名

	public static void main(String[] args) throws IOException {
		AutoGenerator mpg = new AutoGenerator();

		final String outFile = "E:\\mybaitsGenerate";
		System.out.println(outFile);

		// 全局配置
		GlobalConfig gc = new GlobalConfig();
		gc.setOutputDir(outFile + "/src/main/java");
		gc.setOpen(true);// 不打开目录
		gc.setSwagger2(true);
		gc.setFileOverride(true);
		gc.setActiveRecord(false);
		gc.setEnableCache(false);// XML 二级缓存
		gc.setBaseResultMap(true);// XML ResultMap
		gc.setBaseColumnList(false);// XML columList

		gc.setAuthor("hef");

		// 自定义文件命名，注意 %s 会自动填充表实体属性！
		gc.setMapperName("%sMapper");
		gc.setXmlName("%sMapper");
		gc.setServiceName("I%sService");
		gc.setServiceImplName("%sServiceImpl");
		gc.setControllerName("%sController");
		mpg.setGlobalConfig(gc);

		// 数据源配置
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setDbType(DbType.MYSQL);
		dsc.setDriverName("com.mysql.jdbc.Driver");
		dsc.setUsername("root");
		dsc.setPassword("root@hclc");
		dsc.setUrl("jdbc:mysql://127.0.0.1/demo_db?useUnicode=true&characterEncoding=utf8&useOldAliasMetadataBehavior=true&useTimezone=true&serverTimezone=GMT%2B8&useLegacyDatetimeCode=false&allowMultiQueries=true");
		mpg.setDataSource(dsc);

		// 策略配置
		StrategyConfig strategy = new StrategyConfig();
		strategy.setEntityLombokModel(true);
		strategy.setRestControllerStyle(true);
		strategy.setTablePrefix(new String[] { "t_" }); // 此处可以修改为您的表前缀
		strategy.setNaming(NamingStrategy.underline_to_camel); // 表名生成策略
		strategy.setInclude(tableNames); // 需要生成的表
		strategy.setEntityTableFieldAnnotationEnable(true);
		strategy.setEntityLombokModel(true);
		// strategy.setFieldNaming(NamingStrategy.underline_to_camel); //
		// 字段名生成策略
		// strategy.setExclude(new String[]{"test"}); // 排除生成的表
		// 自定义实体父类
		// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
		// 自定义实体，公共字段
		// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
		// 自定义 mapper 父类
		// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
		// 自定义 service 父类
		// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
		// 自定义 service 实现类父类
		// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
		// 自定义 controller 父类
		// strategy.setSuperControllerClass("com.paiye.web.console.controller.BaseController");
		// 【实体】是否生成字段常量（默认 false）
		// public static final String ID = "test_id";
//		 strategy.setEntityColumnConstant(true);
		// 【实体】是否为构建者模型（默认 false）
		// public User setName(String name) {this.name = name; return this;}
		// strategy.setEntityBuilderModel(true);
		mpg.setStrategy(strategy);

		// 包配置
		final CustomizePackageConfig pc = new CustomizePackageConfig();
		pc.setParent("com" + projectPackageName);
//		pc.setEntity(projectPackageName + ".domain" + businessPackageName);
//		pc.setXml(projectPackageName + ".mapper" + businessPackageName);
//		pc.setMapper(projectPackageName + ".mapper" + businessPackageName);
//		pc.setService("api." + projectPackageName);t_business_store_information
//		pc.setServiceImpl(projectPackageName + ".service.impl" + businessPackageName);
//		pc.setController(projectPackageName + ".web.controller" + businessPackageName);
		pc.setDocument(documentPackageName);
		pc.setEntity(businessPackageName);
		pc.setXml("mapper" + businessPackageName);
		pc.setMapper("mapper" + businessPackageName);
		pc.setService("api" + businessPackageName);
		pc.setServiceImpl("service.impl" + businessPackageName);
		pc.setController("web.controller" + businessPackageName);
		mpg.setPackageInfo(pc);

//		 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
		InjectionConfig cfg = new InjectionConfig() {
			@Override
			public void initMap() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
				this.setMap(map);
			}
		};

		List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
		// 调整 xml 生成目录演示
		focList.add(new FileOutConfig("/template/mapper.xml.vm") {
			@Override
			public String outputFile(TableInfo tableInfo) {
				return outFile + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
			}
		});
		// 调整Model生成目录
		focList.add(new FileOutConfig("/template/entity.java.vm") {
			@Override
			public String outputFile(TableInfo tableInfo) {
				String tempPath = pc.getEntity().replaceAll("\\.", "\\\\");
				return outFile + "/src/main/java/com/core/" + tempPath + "/" + tableInfo.getEntityName() + "Model.java";
			}
		});

		// 调整Document生成目录
		focList.add(new FileOutConfig("/template/document.java.vm") {
			@Override
			public String outputFile(TableInfo tableInfo) {
				String tempPath = pc.getDocument().replaceAll("\\.", "\\\\");
				return outFile + "/src/main/java/com/core/" + tempPath + "/" + tableInfo.getEntityName() + "Document.java";
			}
		});
		cfg.setFileOutConfigList(focList);
		mpg.setCfg(cfg);

		// 自定义模板配置
		TemplateConfig tc = new TemplateConfig();
		tc.setController(null);// 关闭默认 controller 生成
		tc.setController("/template/controller.java.vm");
		tc.setEntity(null);
//		tc.setEntity("/template/entity.java.vm");
		tc.setMapper("/template/mapper.java.vm");
		tc.setXml(null);
//		tc.setXml("/template/mapper.xml.vm");
		tc.setService("/template/service.java.vm");
		tc.setServiceImpl("/template/serviceImpl.java.vm");
		mpg.setTemplate(tc);

		// 执行生成
		mpg.execute();

		// 打印注入设置
		System.err.println(mpg.getCfg().getMap().get("abc"));
	}
}
